package com.daguchuangyi.erp_android.search;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;

import com.daguchuangyi.erp_android.R;
import com.daguchuangyi.erp_android.base.CompatStatusBarActivity;
import com.daguchuangyi.erp_android.manager.NetworkManager;
import com.daguchuangyi.erp_android.manager.networkservice.ProductService;
import com.daguchuangyi.erp_android.productlist.classifiaction.ClassificationManager;
import com.jude.utils.JUtils;

import java.util.HashMap;
import java.util.Map;

import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class SearchActivity extends CompatStatusBarActivity {

    private final int RC_SEARCH = 1;
    private final int INTERVAL = 300; //输入时间间隔为300毫秒

    private EditText mSearchEt;
    private RecyclerView mRecyclerView;
    private SearchResultAdapter mResultAdapter;
    private Subscription mSubscription;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == RC_SEARCH) {
                doSearch();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);

        mSearchEt = (EditText) findViewById(R.id.search_et);

        setImmersiveStatusBar(true, Color.WHITE);

        findViewById(R.id.clear_iv).setOnClickListener(v -> {
            mSearchEt.setText(null);
        });

        findViewById(R.id.cancel_tv).setOnClickListener(v -> finish());

        mRecyclerView = (RecyclerView) findViewById(R.id.search_result_rv);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mResultAdapter = new SearchResultAdapter(null);
        mRecyclerView.setAdapter(mResultAdapter);

        mSearchEt.setOnEditorActionListener((textView, actionId, keyEvent) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_UNSPECIFIED) {

                String keytag = mSearchEt.getText().toString().trim();

                if (TextUtils.isEmpty(keytag)) {
                    JUtils.ToastLong("请输入检索关键字");
                    return false;
                }

//                ClassificationManager.getInstance().clear();
                ClassificationManager.getInstance().changeToSearchResultMode(keytag);
                finish();
                return true;
            }
            return false;
        });

        mSearchEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
//                String keyWord = mSearchEt.getText().toString();

                if (mHandler.hasMessages(RC_SEARCH)) {
                    mHandler.removeMessages(RC_SEARCH);
                }
                mHandler.sendEmptyMessageDelayed(RC_SEARCH, INTERVAL);
            }
        });
    }

    public void doSearch() {
        String keyWord = mSearchEt.getText().toString();
        if (TextUtils.isEmpty(keyWord)) {
            mResultAdapter.freshData(null, "");
            return;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("searchWord", keyWord);
        mSubscription = NetworkManager.getInstance().getRetrofit().create(ProductService.class)
                .listProductInfo(map, new HashMap<>())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(productListWrapper -> {
                    JUtils.Log("load search result success.");
                    mResultAdapter.freshData(productListWrapper.getProducts(), keyWord);
                }, throwable -> {
                    JUtils.Log("load search result error : " + throwable.getMessage());
                    throwable.printStackTrace();
                }, () -> {
                    JUtils.Log("load search result completed.");
                });
    }

    @Override
    protected void onDestroy() {
        if (mHandler != null) {
            if (mHandler.hasMessages(RC_SEARCH)) {
                mHandler.removeMessages(RC_SEARCH);
            }
            mHandler = null;
        }
        if (mSubscription != null) {
            if (!mSubscription.isUnsubscribed()) {
                mSubscription.unsubscribe();
            }
            mSubscription = null;
        }
        super.onDestroy();
    }
}
